<template>
  <div class="decoration">
    <div class="header">
      <div class="left">
        <svg-icon icon-class="out" class="icon go_back" @click="goBack"></svg-icon>
        <el-select v-model="currentPage" placeholder="请选择" @change="handleSelectPage" class="theme-page-select"
                   :popper-append-to-body="false">
          <el-option-group
              v-for="group in system"
              :key="group.code"
              :label="group.name">
            <div v-if="group.code === 'theme'" class="custom-option">
              <span @click="showCustomInput = true;customName=''"><i class="el-icon-plus"></i>新建页面</span>
              <el-input style="margin-top: 10px" v-if="showCustomInput" v-model="customName" type="text"
                        placeholder="回车提交" size="mini" @keyup.enter.native="addPage"></el-input>
            </div>
            <el-option
                v-for="item in group.pages"
                :key="item.id"
                :label="item.name"
                :value="item.pageTypeCode">
              <span class="select-row">
                {{ item.name }}
                <span class="ic" style="display: flex; align-items: center">
                 <i class="icon el-icon-copy-document" v-if="item.pageTypeCode.indexOf('theme_auto') >= 0 "
                    @click.stop="handleCopy(item.id)"></i>
                 <i class="icon el-icon-delete" v-if="item.pageTypeCode.indexOf('theme_auto') >= 0 "
                    @click.stop="handleDelCustomPage(item.id)"></i>
                  </span>
              </span>
              <!--              <span style="float: right; color: #8492a6; font-size: 13px">i</span>-->
            </el-option>
          </el-option-group>
        </el-select>
      </div>
      <div class="select-group center">
        <div class="select-btn" @click="handleSelectIcon('pc')" :class="{select: currentIcon === 'pc'}">
          <svg-icon icon-class="desktop"/>
        </div>
        <div class="select-btn" @click="handleSelectIcon('mobile')" :class="{select: currentIcon === 'mobile'}">
          <svg-icon icon-class="mobile"/>
        </div>
        <div class="select-btn" @click="handleSelectIcon('full')" :class="{select: currentIcon === 'full'}">
          <svg-icon icon-class="full"/>
        </div>
      </div>
      <div class="operation-btns">
        <div class="operation-item" @click="handlePublish">
          <svg-icon icon-class="publish" class="icon"/>
          发布
        </div>
        <div class="operation-item" @click="handleView">
          <svg-icon icon-class="view" class="icon"/>
          查看店铺
        </div>
      </div>
    </div>
    <div class="editor_wrapper"
         :style="{right: rightComponent ? '440px' : 0, width: currentIcon === 'mobile' ? '385px' : currentIcon === 'pc' ? 'calc(100% - 440px)' : '100%'}">
      <iframe :src="iframeSrc" ref="iframe" id="iframe" width="100%" height="100%" frameBorder="0" @load="iframeLoad"
              allowFullScreen="true"></iframe>
    </div>
    <div class="form_wrapper" v-loading="loadingCard" v-show="rightComponent">
      <render-right v-if="showComponent" ref="right" :currentPage="currentPage" @deleteCard="deleteCard"
                    @changeCart="handleChangeCard" @resetData="resetData" @sortList="handleSort" :cardList="cardList"
                    :hasForm="hasForm" @tabClick="tabClick" :nav="fixHeaderCards" :foot="fixFooterCards"
                    :available="availableCards" :footsettings="fixFooterCardsSettings"></render-right>
    </div>
  </div>
</template>

<script>
import {mapGetters} from 'vuex';
import RenderRight from './components/right';
import Messager from '@/utils/message';
import {
    getDefaultPageParams,
    getGlobalCards,
    addCustomPage,
    delCustomPage,
    getCards,
    addSiteCard,
    deleteSiteCard,
    sortSiteCard,
    editSiteCard,
    resetSiteCard,
    publishSite
} from '@/api/theme';

export default {
    name: 'index',
    components: {
        RenderRight
    },
    data () {
        return {
            cardId: null,
            isRest: false,
            loadingCard: false,
            showCustomInput: false,
            rightComponent: true,
            dragComponent: false,
            currentIcon: 'pc',
            pageId: '',
            customName: '',
            currentPage: 'home',
            system: [],
            iframeSrc: null,
            systemMap: {
                home: '',
                'series_detail_page': 'collection',
                'product_detail_page': 'products',
                'payment_page': 'checkout-decoration',
                'theme_auto': 'custom-page'
            },
            tabName: 'form-props',
            iframeWin: {},
            cardList: [],
            hasForm: true,
            fixHeaderCards: {},
            fixFooterCards: {},
            fixFooterCardsSettings: {},
            cacheCardList: [],
            availableCards: [],
            showComponent: true,
            shopPagePath: {}
        };
    },
    computed: {
        ...mapGetters(['siteId', 'siteList', 'addCardId', 'projectData']),
        siteInfo () {
            let info = this.siteList.find(res => res.id === Number(this.siteId));
            return info;
        },
        crossUrl () {
            let info = this.siteList.find(res => res.id === Number(this.siteId));
            return process.env.NODE_ENV === 'production' ? 'https://' + info.domainName : 'http://127.0.0.1:3001';
        }
    },
    watch: {
        addCardId (newValue) {
            this.addCard(newValue.id);
        },
        projectData: {
            handler (newVal, oldVal) {
                this.editSiteCard(newVal);
            },
            immediate: false,
            deep: true
        }
    },
    mounted () {
        this.loadingCard = true;
        this.iframeSrc = this.crossUrl + '?decoration=decoration';
        this.iframeWin = this.$refs.iframe.contentWindow;
        this.messager = new Messager(this.iframeWin, '*');
        this.messager.on('shopParams', (value) => {
            const {data} = value;
            this.shopPagePath = data;
            this.filterFormCard(data.name, data.params);
            this.getPageId();
            if (this.currentPage) {
                let name;
                if (this.currentPage.indexOf('theme_auto') >= 0) {
                    name = 'theme_auto';
                } else {
                    name = this.currentPage;
                }
                if (this.tabName === 'form-common') {
                    this.messager.emit('reloadPage', true);
                }
                this.messager.emit('pageReload', {name: name.toLocaleUpperCase(), pageId: this.pageId});
            }
        });
        this.messager.on('pageCardList', (value) => {
            const {data} = value;
            if (this.tabName === 'form-props') {
                this.fixHeaderCards = data['fixHeaderCards'][0];
                this.fixFooterCards = data['fixFooterCards'][0];
                this.fixFooterCardsSettings = data['fixFooterCards'][1] || {};
                this.cardList = data['decorationCards'];
            }
            if (this.tabName === 'form-props') {
                this.cacheCardList = data['decorationCards'];
            }
            this.loadingCard = false;
            this.showComponent = true;
            this.$nextTick(() => {
                if (this.dragComponent) {
                    this.$refs.right.pageCount = 3;
                }
                if (this.isRest) {
                    this.$refs.right.resetCard(this.cardId);
                }
            });
        });
        this.messager.on('commonCardList', (value) => {
            const {data} = value;
            if (this.tabName === 'form-common') {
                this.cardList = data;
                // this.cacheCardList = data;
            }
            this.$nextTick(() => {
                if (this.isRest) {
                    this.$refs.right.resetCard(this.cardId);
                }
            });
        });
    },
    created () {
        this.$store.dispatch('GetLinks');
        this.init();
        this.initAvailableCards();
    },
    beforeDestroy () {
        if (this.messager) {
            this.messager.destroy();
        }
    },
    methods: {
        goBack () {
            window.location.href = '#/';
        },
        iframeLoad () {
            this.$refs.right.setDefault();
            if (this.$refs.right) {
                this.$refs.right.activeTab = 'form-props';
                this.$refs.right.handleTabClick({name: 'form-props'});
            }
        },
        handleSelectPage () {
            if (this.currentPage) {
                this.iframeSrc = '';
                this.loadingCard = true;
                const arr = [];
                this.system.map(res => arr.push(...res.pages));
                const v = this.getPageId();
                const params = this.currentIcon === 'mobile' ? '?decoration=decoration&deviceType=mobile' : '?decoration=decoration';
                this.iframeSrc = v.dataId && this.currentPage.indexOf('theme_auto') < 0 ? `${this.crossUrl}/${this.systemMap[this.currentPage]}/${v.dataId}${params}` : this.currentPage.indexOf('theme_auto') >= 0 ? `${this.crossUrl}/custom-page/${v.id}${params}` : `${this.crossUrl}/${this.systemMap[this.currentPage]}${params}`;
            } else {
                let name;
                name = this.shopPagePath.name.replace('-id', '');
                this.iframeSrc = Object.keys(this.shopPagePath.params).length ? `${this.crossUrl}/${name}/${this.shopPagePath.params.id}` : `${this.crossUrl}/${name}`;
            }
        },
        getPageId () {
            const arr = [];
            this.system.map(res => arr.push(...res.pages));
            const data = arr.find(v => v.pageTypeCode === this.currentPage);
            this.pageId = data ? data.id : null;
            return data;
        },
        // 下拉数据
        async init () {
            const {data} = await getDefaultPageParams(this.siteId);
            data.forEach(res => {
                if (res.code === 'theme') {
                    res.pages.map((aa) => {
                        aa.pageTypeCode = aa.pageTypeCode + aa.id;
                    });
                }
            });
            this.system = data;
        },
        // 获取全局卡片
        initGlobalCard () {
            getGlobalCards(this.siteId).then(res => {
                this.cardList = res.data;
            });
        },
        // 获取可用卡片列表
        initAvailableCards () {
            getCards().then(res => {
                this.availableCards = res.data;
            });
        },
        // 新增卡片
        addCard (id) {
            this.loadingCard = true;
            const arr = [];
            this.system.map(res => arr.push(...res.pages));
            const v = arr.find(v => v.pageTypeCode === this.currentPage);
            let name = this.currentPage.indexOf('theme_auto') >= 0 ? 'theme_auto' : this.currentPage;
            addSiteCard({cardId: id, pageId: v.id, siteId: this.siteId}).then(res => {
                this.messager.emit('pageReload', {name: name.toLocaleUpperCase(), pageId: this.pageId});
            }).catch(() => {
                this.loadingCard = false;
            });
        },
        // 删除卡片
        deleteCard (id) {
            this.$confirm('确认删除吗?', '删除？', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.loadingCard = true;
                let name = this.currentPage.indexOf('theme_auto') >= 0 ? 'theme_auto' : this.currentPage;
                deleteSiteCard(id).then(res => {
                    this.messager.emit('pageReload', {name: name.toLocaleUpperCase(), pageId: this.pageId});
                    this.$refs.right.handleSelect({typeCode: 'cardList', id: 99998});
                }).catch(() => {
                    this.loadingCard = false;
                });
            }).catch(() => {
            });
        },
        // 更新排序
        handleSort (data) {
            this.loadingCard = true;
            this.showComponent = false;
            this.dragComponent = true;
            let name = this.currentPage.indexOf('theme_auto') >= 0 ? 'theme_auto' : this.currentPage;
            sortSiteCard(data).then(res => {
                this.messager.emit('pageReload', {name: name.toLocaleUpperCase(), pageId: this.pageId});
            }).catch(() => {
                this.loadingCard = false;
            });
        },
        // 编辑卡片
        editSiteCard (data) {
            this.loadingCard = true;
            editSiteCard(data).then(() => {
                if (this.tabName === 'form-common') {
                    this.messager.emit('reloadPage', true);
                    this.loadingCard = false;
                } else {
                    let name = this.currentPage.indexOf('theme_auto') >= 0 ? 'theme_auto' : this.currentPage;
                    this.messager.emit('pageReload', {name: name.toLocaleUpperCase(), pageId: this.pageId});
                }
            }).catch(() => {
                this.loadingCard = false;
            });
        },
        // 重置卡片
        resetData (v) {
            this.loadingCard = true;
            this.cardId = v.id;
            resetSiteCard(v.id).then(() => {
                if (this.tabName === 'form-common') {
                    this.messager.emit('reloadPage', true);
                    this.loadingCard = false;
                } else {
                    let name = this.currentPage.indexOf('theme_auto') >= 0 ? 'theme_auto' : this.currentPage;
                    this.messager.emit('pageReload', {name: name.toLocaleUpperCase(), pageId: this.pageId});
                }
                this.isRest = true;
            }).catch(() => {
                this.loadingCard = false;
            });
        },
        // 发布
        handlePublish () {
            this.$confirm('网站将发布到现网供顾客使用，确定发布吗?', '你确定要发布吗？', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                publishSite(this.siteId).then(res => {
                    this.$store.dispatch('CLEAR_FRONT_CACHE');
                    this.$message.success('发布成功');
                });
            }).catch(() => {
            });
        },
        handleChangeCard (e) {
            this.messager.emit('cardId', {name: this.currentPage, id: e.id, typeCode: e.typeCode});
            this.isRest = false;
            this.dragComponent = false;
        },
        filterFormCard (name, params) {
            const white = ['index', 'products-id', 'collection-id', 'address-id', 'placeOrder', 'custom-page-id', 'checkout-decoration', 'payment'];
            const systemMap = {
                index: 'home',
                'collection-id': 'series_detail_page',
                'products-id': 'product_detail_page',
                'placeOrder': 'payment_page',
                'address-id': 'payment_page',
                'checkout-decoration': 'payment_page',
                'payment': 'payment_page',
                'custom-page-id': 'theme_auto'

            };
            if (name === 'custom-page-id') {
                this.currentPage = 'theme_auto' + params.id;
            } else {
                this.currentPage = systemMap[name];
            }

            const hasForm = white.includes(name);
            if (this.tabName === 'form-props') {
                this.cardList = hasForm ? this.cacheCardList : [];
            }
            this.hasForm = hasForm;
        },
        async tabClick (name) {
            this.tabName = name;
            if (name === 'form-common') {
                await this.initGlobalCard();
            } else {
                if (this.currentPage === 'payment_page') {
                    this.messager.emit('pageReload', {name: this.currentPage.toLocaleUpperCase(), pageId: this.pageId});
                } else {
                    this.cardList = this.cacheCardList;
                }
            }
            this.$refs.right.setDefault();
        },
        // 新增自定义页面
        addPage () {
            addCustomPage({siteId: this.siteId, name: this.customName}).then(res => {
                this.showCustomInput = false;
                this.init();
            });
        },
        // 删除自定义页面
        handleDelCustomPage (id) {
            this.$confirm('删除后将不能找回, 请慎重操作!', '确定删除吗？', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                delCustomPage(id).then(res => {
                    this.$message.success('删除成功');
                    window.location.reload();
                });
            }).catch(() => {
            });
        },
        handleCopy (id) {
            this.$copyText(`/custom-page/${id}`).then((e) => {
                this.$message({
                    message: '复制成功',
                    type: 'success'
                });
            });
        },
        // 选择预览pc
        handleSelectIcon (name) {
            this.currentIcon = name;
            this.rightComponent = name !== 'full';
            this.handleSelectPage();
            /* setTimeout(() => {
          if (this.currentPage) {
              let name;
              if (this.currentPage.indexOf('theme_auto') >= 0) {
                  name = 'theme_auto';
              } else {
                  name = this.currentPage;
              }
              if (this.tabName === 'form-common') {
                  this.messager.emit('reloadPage', true);
              }
              this.messager.emit('pageReload', {name: name.toLocaleUpperCase(), pageId: this.pageId});
          }
      }, 800); */
        },
        // 查看店铺
        handleView () {
            window.open(this.crossUrl, '_target');
        }
    }
};
</script>

<style scoped lang="scss">
.decoration {
  position: relative;
  background: #fff;
  z-index: 1;
  width: 100%;
  min-width: 1280px;
  overflow: hidden;
  user-select: none;
  height: calc(100vh - 20px);

  .header {
    box-sizing: border-box;
    width: 100%;
    height: 50px;
    background: #30354d;
    display: flex;
    align-items: center;
    justify-content: space-between;
    color: #fff;
    padding-right: 20px;

    .icon {
      font-size: 20px;
    }

    .left {
      display: flex;
      align-items: center;

      .go_back {
        width: 38px;
        color: #fff;
      }
    }

    .select-group {
      display: flex;
      align-items: center;

      .select-btn {
        width: 56px;
        text-align: center;
        height: 50px;
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;
        font-size: 20px;

        &.select {
          background: #5b99ea;
        }
      }
    }

    .operation-btns {
      display: flex;
      align-items: center;

      .operation-item {
        display: flex;
        align-items: center;
        height: 50px;
        padding: 0 20px;

        .icon {
          margin-right: 12px;
        }

        &:last-child {
          border-left: 1px solid #4b5377;
          border-right: 1px solid #4b5377;
        }

        &:first-child {
          border-left: 1px solid #4b5377;
        }
      }
    }
  }

  .editor_wrapper {
    padding: 10px;
    position: absolute;
    top: 50px;
    left: 0;
    bottom: 0;
    right: 440px;
    background-color: #f6f6f6;
    margin: auto;
  }

  .form_wrapper {
    width: 440px;
    position: absolute;
    top: 50px;
    bottom: 0;
    right: 0;
    background: #fff;
  }
}

.select-row {
  display: flex;
  align-items: center;
  justify-content: space-between;

  .icon {
    display: none;
    &:first-child{
      margin-right: 4px;
    }
  }

  &:hover .icon {
    display: block;
  }
}

.theme-page-select {
  ::v-deep .el-select-group__title {
    font-size: 16px;
    color: #212121;
  }

  .custom-option {
    padding: 10px 20px;
    display: flex;
    justify-content: center;
    flex-direction: column;
    font-size: 14px;
    color: rgb(102, 102, 102);
  }
}
</style>
